package city.spring.modules.personnel.controller;

import city.spring.modules.personnel.entity.EmployeeEntity;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.modules.personnel.vo.EmployeeVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Controller：员工信息
 *
 * @author Panxm
 * @date 2020-04-09 11:39:24
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController extends ApiController {
    private final EmployeeService employeeService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<EmployeeEntity, ?>> entityOrderFields;

    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(EmployeeEntity::getId);
        entityOrderFields.add(EmployeeEntity::getName);
        entityOrderFields.add(EmployeeEntity::getIdCardNum);
        entityOrderFields.add(EmployeeEntity::getSex);
        entityOrderFields.add(EmployeeEntity::getBirthday);
        entityOrderFields.add(EmployeeEntity::getNation);
        entityOrderFields.add(EmployeeEntity::getMarried);
        entityOrderFields.add(EmployeeEntity::getNativePlace);
        entityOrderFields.add(EmployeeEntity::getAttributes);
        entityOrderFields.add(EmployeeEntity::getRegisterAddress);
        entityOrderFields.add(EmployeeEntity::getHomeAddress);
        entityOrderFields.add(EmployeeEntity::getTelPhone);
        entityOrderFields.add(EmployeeEntity::getEmergencyPhone);
        entityOrderFields.add(EmployeeEntity::getEducationalLevel);
        entityOrderFields.add(EmployeeEntity::getPolitical);
        entityOrderFields.add(EmployeeEntity::getTitle);
        entityOrderFields.add(EmployeeEntity::getTitleLevel);
        entityOrderFields.add(EmployeeEntity::getDuties);
        entityOrderFields.add(EmployeeEntity::getProfessionalCategories);
        entityOrderFields.add(EmployeeEntity::getSalaryRange);
        entityOrderFields.add(EmployeeEntity::getOtherBenefits);
        entityOrderFields.add(EmployeeEntity::getContractProbation);
        entityOrderFields.add(EmployeeEntity::getContractStart);
        entityOrderFields.add(EmployeeEntity::getContractEnd);
        entityOrderFields.add(EmployeeEntity::getHiredate);
        entityOrderFields.add(EmployeeEntity::getPersonnelType);
        entityOrderFields.add(EmployeeEntity::getJob);
        entityOrderFields.add(EmployeeEntity::getContractAttachment);
        entityOrderFields.add(EmployeeEntity::getCertificateId);
        entityOrderFields.add(EmployeeEntity::getState);
        entityOrderFields.add(EmployeeEntity::getAllowLogin);
        entityOrderFields.add(EmployeeEntity::getOrgId);
        entityOrderFields.add(EmployeeEntity::getAvatarImg);
    }

    /**
     * 离职
     *
     * @param id
     * @return
     */
    @PutMapping("/quitJob/{id}")
    public Object quitJob(@PathVariable String id, @RequestBody EmployeeEntity entity) {
        employeeService.quitJob(id, entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 获取全部的 <strong>员工信息</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"hiredate"}) Pageable pageable, EmployeeEntity entity) {
        LambdaQueryChainWrapper<EmployeeEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        List<EmployeeEntity> list = lambdaQuery.list();
        return success(list);
    }

    /**
     * 分页获取 <strong>员工信息</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault(sort = {"hiredate"}) Pageable pageable, EmployeeEntity entity) {
        LambdaQueryChainWrapper<EmployeeEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<EmployeeEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        return success(page);
    }

    /**
     * 获取可以使用的员工列表（前端选择用户时使用的用户列表）
     *
     * @param pageable 分页信息
     */
    @GetMapping("selectEmployeeList")
    public Object selectEmployeeList(@PageableDefault Pageable pageable, EmployeeEntity entity) {
        LambdaQueryChainWrapper<EmployeeEntity> lambdaQuery = buildLambdaQuery(entity);
        lambdaQuery.select(EmployeeEntity::getId, EmployeeEntity::getName, EmployeeEntity::getOrgId, EmployeeEntity::getJob, EmployeeEntity::getTelPhone);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<EmployeeEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        return success(page);
    }

    /**
     * 获取一个 <strong>员工信息</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        Page<EmployeeVO> page = new Page<>();
        QueryWrapper<EmployeeVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        IPage<EmployeeVO> iPage = employeeService.staffInfo(page, wrapper);
        List<EmployeeVO> records = iPage.getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>员工信息</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody EmployeeEntity entity) {
        employeeService.saveEmployee(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>员工信息</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody EmployeeEntity entity) {
        entity.setId(id);
        employeeService.updateEmployee(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>员工信息</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        employeeService.deleteEmployee(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>员工信息</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        employeeService.deleteEmployee(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 分页获取 <strong>员工信息</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping("staffInfo")
    public Object staffInfo(@PageableDefault Pageable pageable, EmployeeVO entity) {
        QueryWrapper<? extends EmployeeEntity> queryWrapper = buildQuery(entity);
        return success(employeeService.staffInfo(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<? extends EmployeeEntity> buildQuery(EmployeeVO entity) {
        QueryWrapper<? extends EmployeeEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t1.name", entity.getName());
        wrapper.eq(entity.getBirthday() != null, "t1.birthday", entity.getBirthday());
        wrapper.like(StringUtils.isNotBlank(entity.getNation()), "t1.nation", entity.getNation());
        wrapper.like(StringUtils.isNotBlank(entity.getMarried()), "t1.married", entity.getMarried());
        wrapper.like(StringUtils.isNotBlank(entity.getNativePlace()), "t1.native_place", entity.getNativePlace());
        wrapper.like(StringUtils.isNotBlank(entity.getRegisterAddress()), "t1.register_address", entity.getRegisterAddress());
        wrapper.like(StringUtils.isNotBlank(entity.getEmergencyPhone()), "t1.emergency_phone", entity.getEmergencyPhone());
        wrapper.like(StringUtils.isNotBlank(entity.getEducationalLevel()), "t1.educational_level", entity.getEducationalLevel());
        wrapper.like(StringUtils.isNotBlank(entity.getPolitical()), "t1.political", entity.getPolitical());
        wrapper.like(StringUtils.isNotBlank(entity.getDuties()), "t1.duties", entity.getDuties());
        wrapper.like(StringUtils.isNotBlank(entity.getProfessionalCategories()), "t1.professional_categories", entity.getProfessionalCategories());
        wrapper.like(StringUtils.isNotBlank(entity.getSalaryRange()), "t1.salary_range", entity.getSalaryRange());
        wrapper.like(StringUtils.isNotBlank(entity.getOtherBenefits()), "t1.other_benefits", entity.getOtherBenefits());
        wrapper.like(StringUtils.isNotBlank(entity.getContractPeriod()), "t1.contract_probation", entity.getContractPeriod());
        wrapper.eq(entity.getContractStart() != null, "t1.contract_start", entity.getContractStart());
        wrapper.eq(entity.getContractEnd() != null, "t1.contract_end", entity.getContractEnd());
        wrapper.eq(entity.getHiredate() != null, "t1.hiredate", entity.getHiredate());
        wrapper.eq(entity.getState() != null, "t1.state", entity.getState());
        wrapper.like(StringUtils.isNotBlank(entity.getTitle()), "t1.title", entity.getTitle());
        wrapper.like(StringUtils.isNotBlank(entity.getPersonnelType()), "t1.personnel_type", entity.getPersonnelType());
        wrapper.like(StringUtils.isNotBlank(entity.getJob()), "t1.job", entity.getJob());
        wrapper.like(StringUtils.isNotBlank(entity.getContractAttachment()), "t1.contract_attachment", entity.getContractAttachment());
        wrapper.like(StringUtils.isNotBlank(entity.getCertificateId()), "t1.certificate_id", entity.getCertificateId());
        wrapper.like(StringUtils.isNotBlank(entity.getTitleLevel()), "t1.title_level", entity.getTitleLevel());
        wrapper.like(StringUtils.isNotBlank(entity.getAllowLogin()), "t1.allow_login", entity.getAllowLogin());
        wrapper.like(StringUtils.isNotBlank(entity.getOrgId()), "t1.org_id", entity.getOrgId());
        wrapper.like(StringUtils.isNotBlank(entity.getAvatarImg()), "t1.avatar_img", entity.getAvatarImg());
        wrapper.like(StringUtils.isNotBlank(entity.getHomeAddress()), "t1.home_address", entity.getHomeAddress());
        wrapper.like(StringUtils.isNotBlank(entity.getAttributes()), "t1.attributes", entity.getAttributes());
        wrapper.like(StringUtils.isNotBlank(entity.getJobName()), "t3.name", entity.getJobName());
        wrapper.like(StringUtils.isNotBlank(entity.getOrgName()), "t2.title", entity.getOrgName());
        wrapper.like(StringUtils.isNotBlank(entity.getTelPhone()), "t1.tel_phone", entity.getTelPhone());
        wrapper.like(StringUtils.isNotBlank(entity.getIdCardNum()), "t1.id_card_num", entity.getIdCardNum());

        return wrapper;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<EmployeeEntity> buildLambdaQuery(EmployeeEntity entity) {
        LambdaQueryChainWrapper<EmployeeEntity> lambdaQuery = employeeService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), EmployeeEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getName()), EmployeeEntity::getName, entity.getName());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getIdCardNum()), EmployeeEntity::getIdCardNum, entity.getIdCardNum());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSex()), EmployeeEntity::getSex, entity.getSex());
        lambdaQuery.like(entity.getBirthday() != null, EmployeeEntity::getBirthday, entity.getBirthday());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getNation()), EmployeeEntity::getNation, entity.getNation());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMarried()), EmployeeEntity::getMarried, entity.getMarried());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getNativePlace()), EmployeeEntity::getNativePlace, entity.getNativePlace());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getAttributes()), EmployeeEntity::getAttributes, entity.getAttributes());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRegisterAddress()), EmployeeEntity::getRegisterAddress, entity
                .getRegisterAddress());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getHomeAddress()), EmployeeEntity::getHomeAddress, entity.getHomeAddress());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTelPhone()), EmployeeEntity::getTelPhone, entity.getTelPhone());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getEmergencyPhone()), EmployeeEntity::getEmergencyPhone, entity.getEmergencyPhone());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getEducationalLevel()), EmployeeEntity::getEducationalLevel, entity
                .getEducationalLevel());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPolitical()), EmployeeEntity::getPolitical, entity.getPolitical());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTitle()), EmployeeEntity::getTitle, entity.getTitle());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTitleLevel()), EmployeeEntity::getTitleLevel, entity.getTitleLevel());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDuties()), EmployeeEntity::getDuties, entity.getDuties());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getProfessionalCategories()), EmployeeEntity::getProfessionalCategories, entity
                .getProfessionalCategories());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSalaryRange()), EmployeeEntity::getSalaryRange, entity.getSalaryRange());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getOtherBenefits()), EmployeeEntity::getOtherBenefits, entity.getOtherBenefits());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getContractProbation()), EmployeeEntity::getContractProbation, entity.getContractProbation());
        lambdaQuery.like(entity.getContractStart() != null, EmployeeEntity::getContractStart, entity.getContractStart());
        lambdaQuery.like(entity.getContractEnd() != null, EmployeeEntity::getContractEnd, entity.getContractEnd());
        lambdaQuery.like(entity.getHiredate() != null, EmployeeEntity::getHiredate, entity.getHiredate());
        lambdaQuery.like(entity.getState() != null, EmployeeEntity::getState, entity.getState());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPersonnelType()), EmployeeEntity::getPersonnelType, entity.getPersonnelType());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getJob()), EmployeeEntity::getJob, entity.getJob());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getContractAttachment()), EmployeeEntity::getContractAttachment, entity
                .getContractAttachment());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getCertificateId()), EmployeeEntity::getCertificateId, entity.getCertificateId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getAllowLogin()), EmployeeEntity::getAllowLogin, entity.getAllowLogin());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getOrgId()), EmployeeEntity::getOrgId, entity.getOrgId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getAvatarImg()), EmployeeEntity::getAvatarImg, entity.getAvatarImg());
        return lambdaQuery;
    }

    /**
     * 药师列表 页面展示
     *
     * @param pageable
     * @param entity
     * @return
     */
    @GetMapping("pharmacistList")
    public Object getPharmacistList(@PageableDefault Pageable pageable, EmployeeVO entity) {
        QueryWrapper<? extends EmployeeEntity> queryWrapper = buildQuery(entity);
        return success(employeeService.getPharmacistList(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 医生列表 页面展示
     *
     * @param pageable
     * @param entity
     * @return
     */
    @GetMapping("doctorList")
    public Object getDoctorList(@PageableDefault Pageable pageable, EmployeeVO entity) {
        QueryWrapper<? extends EmployeeEntity> queryWrapper = buildQuery(entity);
        return success(employeeService.getDoctorList(MyBatisUtils.toPage(pageable), queryWrapper));
    }
}
